import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, DatePicker, Input, Select, Modal, Spin } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import '@ant-design/compatible/assets/index.css';
import { costdetail, exportCostbookdetail, queryCityInfo, markFlag, quickMarkFlag, summary } from '../service';
import { useRequest } from '@umijs/hooks';
import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';
import TotalModal from './TotalModal'
import CustomExportModal from './CustomExportModal'
import styles from './index.less';
import { _isFlag, _flightModel, _dOrI, _receiveType, _payStatus, _applyStatus, _isScene, _payTypes } from './_data'

const { Option } = Select;
const { confirm } = Modal
// let hiddenData = null
let isFirst = true;
const CostAnaysis = () => {

  const actionRef = useRef();
  const ref = useRef();

  // 页面loading
  const [btnLoading, handleBtnLoading] = useState(false)
  // 计算高度
  const [height, controlH] = useState(300);
  // 表格折叠
  const [isCollapse, controlC] = useState(true);
  // 总计弹框显隐
  const [totalModalVisible, handleTotalModalVisible] = useState(false);
  // 总计数据
  const [totalData, handleTotalData] = useState({});
  // 自定义导出弹窗显隐
  const [customExportModalVisible, handleCustomExportModalVisible] = useState(false);
  // 存储搜索条件
  const [searchParams, handleSearchParams] = useState({})
  // 是否能导出
  const [exportFlag, handleExportFlag] = useState('')
  // 是否为第一次加载
  // const [firstLoadDate, setFirstLoadDate] = useState(true);

  // 航站接口
  const { data: selectData } = useRequest(queryCityInfo);

  // 格式化航班号
  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }

  // 导出
  const handleExport = () => {
    if (!exportFlag) {
      message.warning('表格数据为空');
    } else {
      handleBtnLoading(true)
      const hide = message.loading('正在导出');
      let res = exportCostbookdetail({ ...searchParams, columnFiledNames: [] }).then(res => {
        let blob = new Blob([res], {
          type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        let elink = document.createElement('a')
        let time = moment(Date.now()).format('YYYY-MM-DD HH_mm_ss')
        elink.download = '异常行李成本分析报表列表' + time + '.xls'
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
        hide();
        handleBtnLoading(false)
        message.success('导出成功');
      }).catch(err => {
        handleBtnLoading(false)
        console.log(err)
      });
    }
  }

  // 标记状态
  const changeFlag = async (rows, flag) => {
    let text = flag === '0' ? '取消标记' : '标记'
    handleBtnLoading(true)
    try {
      await markFlag({
        ids: rows.map(row => row.paxMainKey).toString(),
        status: flag
      });
      handleBtnLoading(false)
      message.success(text + '成功');
      return true;
    } catch (error) {
      handleBtnLoading(false)
      message.error(text + '失败，请重试！');
      return false;
    }
  }

  // 一键标记
  const quickMark = async () => {
    handleBtnLoading(true)
    try {
      await quickMarkFlag({ ...searchParams, receiveType: 1, flag: 1 });
      handleBtnLoading(false)
      message.success('一键标记成功');
      return true;
    } catch (error) {
      handleBtnLoading(false)
      message.error('一键标记失败，请重试！');
      return false;
    }
  }

  // 总计
  const handleTotal = () => {
    handleBtnLoading(true)
    summary(searchParams).then(res => {
      handleTotalData(res)
      handleTotalModalVisible(true)
      handleBtnLoading(false)
    })
  }

  // 自定义导出
  const handleCustomExport = () => {
    if (!exportFlag) {
      message.warning('表格数据为空');
    } else {
      handleCustomExportModalVisible(true)
    }
  }

  // 搜索
  const beforeSearchSubmit = useCallback(params => {

    params['beginDate'] = params.beginDate ? params.beginDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    // if (!isCollapse) {
    //   if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
    //     ref.current.setFieldsValue({
    //       beginDate: moment(),
    //       endDate: moment()
    //     })
    //   }
    //   handleSearchParams(params)
    //   return params
    // } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('beginDate') === -1) {
          params.beginDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
        handleSearchParams({ ...params })
        return { ...params }
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        isFirst = true;
        ref.current.setFieldsValue({
          beginDate: moment(),
          endDate: moment()
        })
        // hiddenData = null
        handleSearchParams(params)
        return params
      }
    // }
  }, [isCollapse]);

  // 切换清空搜索
  // useEffect(() => {
  //   hiddenData = null
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, [])

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 455);
    } else {
      controlH(document.body.clientHeight - 565);
    }
  }, [isCollapse])
  useEffect(() => {
    return () => {
      isFirst = true;
    }
  }, [])
  const columns = [
    {
      title: '航班起始日期',
      dataIndex: 'beginDate',
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '航班结束日期',
      dataIndex: 'endDate',
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '支付起始日期',
      dataIndex: 'payBeginDate',
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '支付结束日期',
      dataIndex: 'payEndDate',
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '财务标记',
      dataIndex: 'isFlag',
      fixed: 'left',
      width: 120,
      render: (_, record) => {
        return record.isFlag === '标记' ? <span>已标记</span> : ''
      },
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _isFlag.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      }
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      fixed: 'left',
      width: 120,
      hideInSearch: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      fixed: 'left',
      width: 90,
      renderFormItem: (_, { value, onChange }) => {
        return <Input
          onChange={e => {
            let value = formatFlightNo(e.target.value);
            onChange(value);
          }}
          value={value}
          allowClear
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '起飞航站',
      dataIndex: 'org',
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '到达航站',
      dataIndex: 'dst',
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '起飞航站',
      dataIndex: 'orgName',
      width: 100,
      hideInSearch: true

    },
    {
      title: '到达航站',
      dataIndex: 'dstName',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '发生地',
      dataIndex: 'serviceCity',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '财务机型',
      dataIndex: 'flightModel',
      width: 90,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _flightModel.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      }
    },
    {
      title: '地区类别',
      dataIndex: 'flightType',
      width: 90,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _dOrI.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      }
    },
    {
      title: '原因',
      dataIndex: 'innerReason',
      width: 160,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '补偿单号',
      dataIndex: 'orderId',
      width: 160,
      hideInSearch: true,
    },
    {
      title: '补偿类型',
      dataIndex: 'luggageCompensationType',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '事故单号',
      dataIndex: 'accidentId',
      width: 120,
      hideInSearch: true,
      ellipsis: true
    },
    {
      title: '姓名',
      width: 120,
      dataIndex: 'paxName',
    },
    {
      title: '票号',
      width: 160,
      dataIndex: 'tktNo',
      ellipsis: true
    },
    {
      title: '授权金额',
      dataIndex: 'currentAmount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '支付金额',
      dataIndex: 'payAmount',
      width: 100,
      hideInSearch: true
    },
    {
      title: '差异',
      dataIndex: 'difference',
      width: 90,
      hideInSearch: true
    },
    {
      title: '领取状态',
      dataIndex: 'receiveType',
      width: 100,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _receiveType.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      }
    },
    {
      title: '财务状态',
      dataIndex: 'financialStatus',
      width: 100,
      hideInSearch: true
    },
    {
      title: '申领单号',
      dataIndex: 'applyCode',
      width: 160,
      ellipsis: true
    },
    {
      title: '支付状态',
      dataIndex: 'payStatus',
      width: 100,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _payStatus.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      }
    },
    {
      title: '审核状态',
      dataIndex: 'applyStatus',
      width: 100,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _applyStatus.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      }
    },
    {
      title: '领取渠道',
      dataIndex: 'isScene',
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _isScene.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '领取渠道',
      dataIndex: 'scene',
      width: 100,
      hideInSearch: true
    },
    {
      title: '支付方式',
      dataIndex: 'payTypes',
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            mode="multiple"
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : undefined}
          >
            {
              _payTypes.map(item => (
                <Option key={item.id}>{item.name}</Option>
              ))
            }
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      width: 100,
      hideInSearch: true
    },
    {
      title: '户名',
      dataIndex: 'accountName',
      width: 120,
      hideInSearch: true
    },
    {
      title: '开户银行',
      dataIndex: 'bankName',
      width: 160,
      hideInSearch: true
    },
    {
      title: '账号',
      dataIndex: 'moneyAccount',
      width: 160,
      hideInSearch: true
    },
    {
      title: '支付日期',
      dataIndex: 'payDate',
      width: 120,
      hideInSearch: true
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      width: 120,
      hideInSearch: true
    },
    {
      title: '支付流水号',
      dataIndex: 'returnOrderNo',
      width: 120,
      hideInSearch: true
    },
    {
      title: '到期日',
      dataIndex: 'expiryDate',
      width: 120,
      hideInSearch: true
    },
    {
      title: '权限审批人职务及姓名',
      dataIndex: 'auditInfo',
      width: 180,
      hideInSearch: true
    },
  ];

  return (
    <div>
      <Spin spinning={btnLoading}>
        <ProTable
          actionRef={actionRef}
          formRef={ref}
          rowKey="accidentId"
          className={styles.costAnaysis}
          headerTitle={
            <div>
              <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>成本分析表</span>
            </div>
          }
          options={{ density: false, fullScreen: true, reload:false, setting: true }}
          rowSelection={{}}
          beforeSearchSubmit={beforeSearchSubmit}
          search={{
            span: 6,
            onCollapse: val => {
              controlC(val);
              // if (!val && hiddenData) {
              //   ref.current.setFieldsValue({
              //     payBeginDate: hiddenData.payBeginDate,
              //     payEndDate: hiddenData.payEndDate,
              //     isFlag: hiddenData.isFlag,
              //     flightNo: hiddenData.flightNo,
              //     org: hiddenData.org,
              //     dst: hiddenData.dst,
              //     serviceCity: hiddenData.serviceCity,
              //     flightModel: hiddenData.flightModel,
              //     flightType: hiddenData.flightType,
              //     paxName: hiddenData.paxName,
              //     tktNo: hiddenData.tktNo,
              //     receiveType: hiddenData.receiveType,
              //     applyCode: hiddenData.applyCode,
              //     payStatus: hiddenData.payStatus,
              //     applyStatus: hiddenData.applyStatus,
              //     isScene: hiddenData.isScene,
              //     payTypes: hiddenData.payTypes,
              //   })
              // } else {
              //   hiddenData = ref.current.getFieldsValue()
              // }
            }
          }}
          toolBarRender={(action, { selectedRows }) => [
            <AuthComponent authCode="banksearchSystem.costAnaysis.mark">
              <Button type="primary" size="small" onClick={() => {
                if (selectedRows.length === 0) {
                  message.error("请选择需要标记的条目 ！")
                } else {
                  let receiveFlag = ''
                  selectedRows.forEach(element => {
                    if (element.receiveType !== '已领取' || element.isFlag === '标记') {
                      receiveFlag = true
                    }
                  });
                  if (receiveFlag) {
                    confirm({
                      title: '提示',
                      content: '只能选择‘未标记’并且领取状态为‘已领取’的条目',
                    })
                  } else {
                    confirm({
                      title: '提示',
                      content: `共选择${selectedRows.length}条需要标记的条目，是否进行标记操作？`,
                      cancelText: '取消',
                      okText: '确认',
                      onOk: async () => {
                        const result = await changeFlag(selectedRows, '1')
                        if (result) {
                          actionRef.current.reload();
                        }
                      }
                    })
                  }
                }
              }}>
                标记
            </Button>
            </AuthComponent>,
            <AuthComponent authCode="banksearchSystem.costAnaysis.allMark">
              <Button type="default" size="small" onClick={() => {
                confirm({
                  title: '提示',
                  content: '为了保持数据一致性，请页面查询完成后不要修改查询条件，否则可能会造成标记的条目与查询到的条目不一致！',
                  cancelText: '取消',
                  okText: '确认',
                  onOk: async () => {
                    costdetail({ ...searchParams, receiveType: [1] }).then(res => {
                      if (res.total === 0) {
                        confirm({
                          title: '提示',
                          content: '无可标记操作的条目!',
                        })
                      } else {
                        confirm({
                          title: '提示',
                          content: `即将标记${res.total}条条目，是否继续操作？`,
                          onOk: async () => {
                            const result = await quickMark()
                            if (result) {
                              actionRef.current.reload();
                            }
                          }
                        })
                      }
                    })
                  }
                })
              }}>
                一键标记
            </Button>
            </AuthComponent>,
            <AuthComponent authCode="banksearchSystem.costAnaysis.cancelMark">
              <Button type="default" size="small" onClick={() => {
                if (selectedRows.length === 0) {
                  message.error("请选择需要取消标记的条目 ！")
                } else {
                  let unuseful = selectedRows.filter(item => { return item.isFlag !== '标记' })
                  confirm({
                    title: '提示',
                    content: `共选择${selectedRows.length}条需要取消标记的条目，${unuseful.length}条无效条目，是否继续进行取消标记操作？`,
                    cancelText: '取消',
                    okText: '确认',
                    onOk: async () => {
                      const result = await changeFlag(selectedRows, '0')
                      if (result) {
                        actionRef.current.reload();
                      }
                    }
                  })
                }
              }}>
                取消标记
            </Button>
            </AuthComponent>,
            <AuthComponent authCode="banksearchSystem.costAnaysis.total">
              <Button type="default" size="small" onClick={() => handleTotal()}>
                总计
            </Button>
            </AuthComponent>,
            <AuthComponent authCode="banksearchSystem.costAnaysis.export">
              <Button icon="download" type="primary" onClick={() => handleExport()} size="small">
                导出
            </Button>
            </AuthComponent>,
            <AuthComponent authCode="banksearchSystem.costAnaysis.customExport">
              <Button icon="download" type="primary" onClick={() => handleCustomExport()} size="small">
                自定义导出
              </Button>
            </AuthComponent>
          ]}
          tableAlertRender={false}
          postData={data => {
            if (data.length === 0) {
              handleExportFlag(false)
            } else {
              handleExportFlag(true)
            }
            return data
          }}
          request={params => {
            let troubleshootArr = ['payBeginDate','payEndDate','isFlag','flightNo','org','dst','serviceCity','flightModel','flightType','paxName','tktNo','receiveType','applyCode','payStatus','applyStatus','isScene','payTypes'];
            if (isFirst) {
              isFirst = false;
              if (!params['beginDate'] && !params['endDate']) {
                params['beginDate'] = moment().format('YYYY-MM-DD')
                params['endDate'] = moment().format('YYYY-MM-DD')
                ref.current.setFieldsValue({
                  beginDate: moment(),
                  endDate: moment()
                })
              }
            }else{
              let otherParamsHavaValue = false;
              for (const key of troubleshootArr) {
                const element = params[key];
                if (element || element?.length > 0) {
                  otherParamsHavaValue = true;
                  break;
                }
              }
              if (!otherParamsHavaValue) {
                if (!params['beginDate'] && !params['endDate']) {
                  params['beginDate'] = moment().format('YYYY-MM-DD')
                  params['endDate'] = moment().format('YYYY-MM-DD')
                  ref.current.setFieldsValue({
                    beginDate: moment(),
                    endDate: moment()
                  })
                }
              }
            }
            handleSearchParams({...searchParams, ...params})
            return costdetail(params)
          }}
          columns={columns}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
            defaultPageSize: 20,
            pageSizeOptions: ['20', '30', '40']
          }}
          scroll={{ x: 1300, y: height }}
        />
      </Spin>
      <TotalModal totalModalVisible={totalModalVisible} totalData={totalData} onCancel={() => handleTotalModalVisible(false)} />
      <CustomExportModal searchParams={searchParams} customExportModalVisible={customExportModalVisible} columns={columns} onCancel={() => handleCustomExportModalVisible(false)} />
    </div>
  );
};

export default Form.create()(CostAnaysis);
